package vista;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;

import utilidades.UtilidadesDeArchivos;

public class Audio {
	private static Clip clip;
	private static Line line;
	
	private Audio(){}
		
	// plays a sound if no other sound is beeing played
	public static void playOnTop(String rutaRelativaArchivoAudio) {
		try {
			InputStream in = new FileInputStream(UtilidadesDeArchivos.completarRuta(rutaRelativaArchivoAudio));
	        AudioInputStream inputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(in));

	        AudioFormat format = inputStream.getFormat();
	        DataLine.Info info = new DataLine.Info(Clip.class, format);
	   
	        Clip clipi = (Clip)AudioSystem.getLine(info);
	        clipi.open(inputStream);
	        clipi.start();
	    } catch (Exception e) {
	        System.err.println(e.getMessage());
	    }		
	}
	
	// plays a sound
	public static void playSound(String rutaRelativaArchivoAudio) {
		try {
			InputStream in = new FileInputStream(UtilidadesDeArchivos.completarRuta(rutaRelativaArchivoAudio));
	        AudioInputStream inputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(in));

	        AudioFormat format = inputStream.getFormat();
	        DataLine.Info info = new DataLine.Info(Clip.class, format);

	        if(clip == null || !clip.isRunning()){	
	        	if(line != null && line.isOpen())
	        		line.close();
	        	
	        	line = AudioSystem.getLine(info);
	        	clip = (Clip)line;
	        	clip.open(inputStream);
	        	clip.start();
	        }
	    } catch (Exception e) {
	        System.err.println(e.getMessage());
	    }		
	}

}
